<template>
  <div class="flex overflow-auto pt-[24px]">
    <div class="m-auto w">
      <div class="bg-[#fff] p-4 flex gap-4">
        <div
          v-for="(item, i) in imageList"
          :key="item.id"
          class="flex gap-2"
          :class="`${item.selected ? 'active' : ''}`"
        >
          <div class="relative" @click="onClickImage(item, i)" :class="`${itemClass}`">
            <img
              ref="imageRefs"
              class="object-cover w-full h-full overflow-hidden rounded-lg"
              :src="item.url"
              alt=""
            />
            <!-- <div @click.stop="delImage(item)" class="del-item">
              {{ $t("button.删除") }}
            </div> -->
          </div>
          <div v-if="cropData?.length > 0" class="flex items-end gap-2 crop-wrapper">
            <template v-if="!loading">
              <div
                v-for="item in cropData"
                :key="item"
                class="relative flex items-center justify-center overflow-hidden rounded-lg crop"
                :class="`${item.selected ? 'on' : ''}`"
                @click="onClickCrop(item)"
              >
                <div
                  :style="{
                    backgroundImage: `url('${item.image.url}')`,
                    width: `100%`,
                    height: `${(item.data[3] - item.data[2]) / item.rate}px`,
                    backgroundPosition: `${-item.data[0] / item.rate}px ${
                      -item.data[2] / item.rate
                    }px`,
                    backgroundSize: `${item.width / item.rate}px ${
                      item.height / item.rate
                    }px`,
                    backgroundRepeat: 'no-repeat',
                  }"
                ></div>

                <div v-if="item.selected" class="brage">
                  <n-icon :size="18">
                    <CheckmarkOutline></CheckmarkOutline>
                  </n-icon>
                </div>
              </div>
            </template>
            <n-spin v-else></n-spin>
          </div>
        </div>

        <div
          v-if="imageList.length < 2"
          :class="itemClass"
          class="add-item"
          @click="onClickShowUpload"
        >
          <!-- <n-icon :size="40">
            <ImageOutline></ImageOutline>
          </n-icon> -->
          <img class="w-[36px]" src="/images/icons/uploadImage.png" />
        </div>
      </div>
      <searchProduct ref="searchProductRef" @loadCallback="loadCallback"></searchProduct>
    </div>
    <uploadImage ref="uploadImageRef"></uploadImage>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ImageOutline, CheckmarkOutline } from "@vicons/ionicons5";
import { Session } from "@/utils/storage";
import searchProduct from "@/components/searchProduct.vue";
import uploadImage from "@/components/uploadImage.vue";
import bus from "@/utils/mitt";
import { useRouter } from "vue-router";
const itemClass =
  "item bg-white rounded-lg w-[102px] h-[102px] overflow-hidden flex items-center justify-center cursor-pointer";
const imageList = ref([]);
const uploadImageRef = ref();
const searchProductRef = ref();
const router = useRouter();
const imageRefs = ref();
const imageIndex = ref(0);
const loading = ref(false);
onMounted(() => {
  bus.on("updateImageList", () => {
    loadImage();
  });
  loadImage();
});
onUnmounted(() => {
  bus.off("updateImageList");
  Session.set("imageList", []);
});

const loadImage = () => {
  imageList.value = Session.get("imageList");
  if (imageList.value.length == 0) {
    router.push("/");
  }
  let index = imageList.value.length - 1;
  onClickImage(imageList.value[index], index);
};

const onClickImage = (item, index) => {
  if (!item.id) return;
  imageList.value.forEach((e) => {
    e.selected = e.id == item.id;
  });

  imageIndex.value = index;
  loading.value = true;
  searchProductRef.value.pageLoaded({
    type: "image",
    imageId: item.id,
  });
};
const onClickCrop = (item) => {
  item.selected = true;
  cropData.value.forEach((e) => {
    e.selected = e.region == item.region;
  });
  imageIndex.value = item.imageIndex;
  searchProductRef.value.pageLoaded({
    type: "image",
    imageId: item.image.id,
    region: item.region,
  });
};

const onClickShowUpload = () => {
  uploadImageRef.value.show();
};

const cropData = ref([]);
const loadCallback = (data, imageId) => {
  if (!data.picRegionInfo?.yoloCropRegion) {
    //当前图片没有可用主体
    loading.value = false;
    cropData.value = [];
    return;
  }
  let cropList = data.picRegionInfo.yoloCropRegion.split(";");
  let _cropData = [];

  let width = imageRefs.value[imageIndex.value].naturalWidth;
  let height = imageRefs.value[imageIndex.value].naturalHeight;
  let image = imageList.value.find((x) => x.id == imageId);
  for (let i = 0; i < cropList.length; i++) {
    const crop = cropList[i];
    let cropArray = crop.split(",");
    _cropData.push({
      selected: crop == data.picRegionInfo.currentRegion,
      region: crop,
      data: cropArray,
      image,
      width,
      height,
      imageIndex,
      rate: (cropArray[1] - cropArray[0]) / 90,
    });
  }
  cropData.value = _cropData;
  loading.value = false;
  // console.log("%c Line:192 🥚", "color:#e41a6a", cropData);
};

const delImage = (item) => {
  imageList.value = imageList.value.filter((x) => x.id != item.id);
  Session.set("imageList", imageList.value);
};
</script>

<style lang="scss" scoped>
.item {
  border: 2px solid rgb(48 48 48 / 20%);
  position: relative;
  // .brage {
  //   position: absolute;
  //   right: 0;
  //   top: 0;
  //   background: var(--main-color);
  //   color: white;
  //   border-bottom-left-radius: 8px;
  //   display: flex;
  //   align-items: center;
  // }
  &:hover {
    .del-item {
      bottom: 0px;
    }
  }
  .del-item {
    position: absolute;
    bottom: -24px;
    color: white;
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    text-align: center;
    transition: all 0.3s;
  }
}
.add-item {
  border: 2px dashed rgb(48 48 48 / 20%);
  color: rgb(48 48 48 / 20%);
  &:hover {
    border: 2px dashed var(--main-color);
  }
}

.crop-wrapper {
  display: none;
}
.active {
  // border: 1px solid var(--main-color);
  .crop-wrapper {
    display: flex !important;
  }
}
.crop {
  width: 90px;
  height: 90px;
  cursor: pointer;
  border: 1px solid rgb(48 48 48 / 20%);
  &.on {
    border: 1px solid var(--main-color);
  }
  .brage {
    position: absolute;
    right: 0;
    top: 0;
    background: var(--main-color);
    color: white;
    border-bottom-left-radius: 8px;
    display: flex;
    align-items: center;
  }
}
.image-crop {
  width: 90px;
  height: 90px;

  background-repeat: no-repeat;
  // background-size: cover;
}
</style>
